package frontend

import (
	"context"
	"embed"
	"io/fs"
	"net/http"

	"quipus/internal/profile"
	"quipus/internal/utils"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/compress"
	"github.com/gofiber/fiber/v2/middleware/filesystem"
)

//go:embed all:dist
var embeddedFiles embed.FS

type FrontendService struct {
	Profile *profile.Profile
	// Store   *store.Store
}

func NewFrontendService(profile *profile.Profile) *FrontendService {
	return &FrontendService{
		Profile: profile,
		// Store:   store,
	}
}

func (*FrontendService) Serve(_ context.Context, app *fiber.App) {
	skipper := func(ctx *fiber.Ctx) bool {
		return utils.HasPrefixes(ctx.Path(), "/api", "/ws", "/wss", "/qps.api.v1")
	}

	// 使用 Fiber 的 Gzip 中间件来压缩响应
	app.Use(compress.New(compress.Config{
		Level: compress.Level(5),
	}))

	// 为 assets 组设置中间件和静态文件服务
	assets := app.Group("assets")
	assets.Use(func(c *fiber.Ctx) error {
		if skipper(c) {
			return c.Next()
		}
		c.Response().Header.Set("Cache-Control", "max-age=31536000, immutable")
		return c.Next()
	})
	// assets.Static("/", "dist/assets")
	assets.All("/*", filesystem.New(filesystem.Config{
		Root:         embed_os("dist/assets"),
		NotFoundFile: "index.html",
		Index:        "index.html",
	}))

	// 为其他静态文件设置中间件和静态文件服务
	app.Use(func(c *fiber.Ctx) error {
		if skipper(c) {
			return c.Next()
		}
		c.Response().Header.Set("Cache-Control", "max-age=31536000, immutable")
		return c.Next()
	})
	// app.Static("/", "dist")
	app.All("/*", filesystem.New(filesystem.Config{
		Root:         embed_os("dist"),
		NotFoundFile: "index.html",
		Index:        "index.html",
	}))
}

func embed_os(path string) http.FileSystem {
	fs, err := fs.Sub(embeddedFiles, path)
	if err != nil {
		panic(err)
	}
	return http.FS(fs)
}

func getFileServer(path string) http.Handler {
	return http.FileServer(embed_os(path))
}
